% Given a guess for price index P, domestic spending S, and wage w, solve for
% firm-level behavior (sD,sX), and compute P-Pnew, S-SP, and S-SP2, where
% Pnew is implied the price index, SP is the level of domestic spending
% implied by the labor market clearing condition, and SP2 is the level of
% domestic spending implied by the definition of domestic spending
% (equation (26) of the paper).
% An equilibrium is a zero of this function.

function MSE = FindFixedPoint(x,param, phi, fc_norm, fx_norm,FXM_norm,FX_norm,FM_norm,SDM,SDXM,zvec,yvec)

% Guess for price index, domestic spending, and wages
P = abs(x(1)); 
S = abs(x(2));
w = abs(x(3));

g = param.gamma; 
sg = param.sg;
eta = param.eta;
qD = param.qD;
theta = param.theta;
z = param.z;
tau = param.tau;
bl = param.bl;

% Re-scale fixed costs:
fc = (P^((sg-1)*(1-g) + 1/eta ) * S /w * (qD*z)^(-1/eta) * (sg-1)^sg / (sg^sg) * (g*qD)^(g*(sg-1)) * (1-g)^((1-g)*(sg-1)) *eta * g * w^(-(sg-1)*(1-g))).^(-1) * fc_norm;
fx = ((1+tau)^(theta *(sg-1)) * P^((sg-1)*(1-g*(1-theta))) * S * (g*qD)^(g*(sg-1)*(1-theta)) * (1-g)^((1-g)*(sg-1)*(1-theta)) *  (sg-1)^((1-theta)*(sg-1)) * sg^(sg*(theta-1)) * bl^(-theta) * (1/w) ^(-(theta-1)*((sg-1)*(1-g)+1)) * (theta-1)/theta).^(-1/(1-theta)) * fx_norm;
FXM = (sg^(-sg) * (sg-1)^(sg-1) * (g*qD)^(g*(sg-1)) * (1-g)^((1-g)*(sg-1)) * P^((sg-1)*(1-g) ) * S * (1/w)^((sg-1)*(1-g)+1))^(-1) * FXM_norm ;
FM = (sg^(-sg) * (sg-1)^(sg-1) * (g*qD)^(g*(sg-1)) * (1-g)^((1-g)*(sg-1)) * P^((sg-1)*(1-g) ) * S  * (1/w)^((sg-1)*(1-g)+1))^(-1) * FM_norm ;
FX = (sg^(-sg) * (sg-1)^(sg-1) * (g*qD)^(g*(sg-1)) * (1-g)^((1-g)*(sg-1)) * P^((sg-1)*(1-g) ) * S  * (1/w)^((sg-1)*(1-g)+1))^(-1) * FX_norm;
 
% Domestic and export shares:
[sD,sX,~,~] =  SolveModel(phi,fc,fx,FXM,FX,FM,SDM,SDXM,zvec,yvec, param);

% Given re-scaled fixed costs and domestic and export shares back out
% equilibrium spending and price
[SP,SP2,Pnew,~,~,~] = GEobjects(w,sD, sX, phi,fc,fx, param);

% Construct MSE

MSE(1) = (P - Pnew);
MSE(2) = (S - SP);
MSE(3) = (S-SP2);

end